$(function () {

    // 配置路径
    var pageUrl = config.urlAnaConfig.testPath;
    // 获取Cookie
    function getCookie(name){
        var strcookie = document.cookie;//获取cookie字符串
        var arrcookie = strcookie.split("; ");//分割
    //       console.log(arrcookie);
        //遍历匹配
        for ( var i = 0; i < arrcookie.length; i++) {
            var arr = arrcookie[i].split("=");
                if (arr[0] ==name){
                    return arr[1];
                }
        }
        return "";
    }
    var name = "tokenval";
    // tiken值
    var cookie_value = getCookie(name);
    console.log(cookie_value);
    var name1 = "userName";
    // 用户名值
    var cookie_value1 = getCookie(name1);
    $(".userName").html(cookie_value1);
    $(".nav-usename").html(cookie_value1);
    // 默认数据
    var mrData1 = "2018Q1";
    var mrData2 ="天猫";
    // 下拉数据
    $('#usertype').selectpicker({
             noneSelectedText : '请选择',
         });
    $.ajax({
        url: pageUrl+'/api/productstream/getyearsandseasonandchannel',
        type: 'POST',
        dataType: 'json',
        headers: {
            Authorization: 'Bearer '+cookie_value
        },
        success: function (data) {
            var msg = '';
            if (data) {
                if (data.code === 200) {
//                  时间
                    
                    var yearsName = data.data.years;
                    //console.log(yearsName)
                    var yearsNameF = $(".details2").next('ul');
                    var myYearsName = yearsName;
                    /*for in 循环*/
                     for(var i in myYearsName){
                         var text="<li>" + myYearsName[i] + " </li>";
                         yearsNameF.append(text);
                     };
                    // 渠道
                    var storeName = data.data.channels;
                    var storeNameF = $(".details1").next('ul');
                    var myStoreName = storeName;
                    /*for in 循环*/
                     for(var i in myStoreName){
                         var text="<li>" + myStoreName[i] + " </li>";
                         storeNameF.append(text);
                     };

                     $('.det_det2').on('click','li',function(){
                         //console.log('hello')
                         var chooseTime = $(this).html();
                         $("#usertype option").remove();
                         $('#usertype').attr("disabled",false);
                         $('#usertype').selectpicker('refresh');
                         $.ajax({
                            url: pageUrl+'/api/productstream/getseasonsbyyear',
                            type: 'POST',
                            dataType: 'json',
                            data:{
                                year:chooseTime
                            },
                            headers: {
                                Authorization: 'Bearer '+cookie_value
                            },
                            success: function (data) {
                                var msg = '';
                                if (data) {
                                    if (data.code === 200) {
                                        var platForm = data.data.seasons
                                         //                  季度
                                        var platFormF = $("#usertype");
                                        var myPlatForm = platForm;
                                        /*for in 循环*/
                                        for(var i in myPlatForm){
                                        var ss="<option value='" + myPlatForm[i] + "'>" + myPlatForm[i] + "</option>";
                                            platFormF.append(ss)
                                            $('#usertype').selectpicker('refresh');
                                            /*$(".commodity1Time2 option").eq(0).val(myPlatForm[1]);
                                            $(".commodity1Time2 option").eq(1).val(myPlatForm[2]);
                                            $(".commodity1Time2 option").eq(2).val(myPlatForm[3]);
                                            $(".commodity1Time2 option").eq(3).val(myPlatForm[4]);*/
                                        };

                                    }
                                }
                            },
                            error: function () {
                                alert("数据错误");
                                // window.location.href="login.html";
                            }

                        });
                     });

                }
            }
        },
        error: function () {
            alert("数据错误");
            // window.location.href="login.html";
        }

    });


    $.ajax({
        url: pageUrl+'/api/common/getaccesstoken',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            var msg = '';
            if (data) {
                var commodityTime1 = mrData1;
                var commodityTime2 = mrData2;
                var accessToken = data.data.accessToken.value;
                console.log(accessToken);
                //alert(11)
                // var accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkZDQmFtTFdha2tLWVhTMFFEdDJYcVFha2JPRSIsImtpZCI6IkZDQmFtTFdha2tLWVhTMFFEdDJYcVFha2JPRSJ9.eyJhdWQiOiJodHRwczovL2FuYWx5c2lzLmNoaW5hY2xvdWRhcGkuY24vcG93ZXJiaS9hcGkiLCJpc3MiOiJodHRwczovL3N0cy5jaGluYWNsb3VkYXBpLmNuLzlhZWJiZmVkLTc1MmMtNDVhYy1iZDhiLTg2ODczODZiYjg0ZS8iLCJpYXQiOjE1NTEyNTkwNTgsIm5iZiI6MTU1MTI1OTA1OCwiZXhwIjoxNTUxMjYyOTU4LCJhY2N0IjowLCJhY3IiOiIxIiwiYWlvIjoiQVNRQTIvOENBQUFBVEI1bDYzL1p4cksvWE1KMD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cG4iOiJ6aWthaUBzYXB6ei5wYXJ0bmVyLm9ubXNjaGluYS5jbiIsInV0aSI6ImRMTENOSkJNNTBPd3dxQlZtSkVtQUEiLCJ2ZXIiOiIxLjAiLCJ3aWRzIjpbIjYyZTkwMzk0LTY5ZjUtNDIzNy05MTkwLTAxMjE3NzE0NWUxMCJdfQ.U7hDVy8gGDVBe3Ynu8-CQDWBL-JK3DWXEuHY_0vbgPDvbZk6yE1ES1VGI1wE00VLp5xBHahof4GVXJlhnoJWGSu6ZVDPu6_wDODSneTOXff58JXKa5oVvN5lf7ZA_vgMkpiWBPdpK4w8GQkGgRUvJvlUGy7e9Lh11JfDwbKVPUvtyZ03PDPPRzkUErOyBfIJy4Ups4jsN8EwYYMgcJ3lkQRU2xmPHAKOw5QSEJj6k3WEjmYhmeQNHpRFxxPF2PTaoDKZ4EM5sqdyF691k4MtHowhL68uuEtU7NgpDgGPwP-RU925nk6Nf6fNFsnn50jxvH_lYCKHd8PrRBRzNc8VGg";
                // Read embed application token from Model
                // Read embed URL from Model
                var embedUrl = "https://app.powerbi.cn/reportEmbed?reportId=6f4afd96-4aee-4f73-aba3-75cf9f483614&groupId=ccc12464-fcfc-4fd0-ac4b-877eaad6b69b&filter=platform/platform eq"+" '"+commodityTime2+"' "+"and season/code eq "+"'"+commodityTime1+"'";
                tu1(accessToken,embedUrl);
            }
        },
        error:  function (XMLHttpRequest, textStatus, errorThrown) {
                    // msg
                    var errorTips = XMLHttpRequest.responseJSON.msg;
                    if (errorTips=='Division by zero'){
                        $(".layer1 .content").html("数据错误");
                        $(".layer1").show();
                        console.log(errorTips);
                    } else if(errorTips=='Token has expired'){
                        $(".layer1 .content").html("令牌过期");
                        $(".layer1").show();
                        window.location.href="login.html";
                    }


                }

    });


    // 图1
    function tu1(accessToken,embedUrl) {
        accessToken = accessToken;
        embedUrl = embedUrl;
        console.log(embedUrl);
        var embedReportId = "6f4afd96-4aee-4f73-aba3-75cf9f483614";
        // Get models. models contains enums that can be used.
        var models = window['powerbi-client'].models;
        // Embed configuration used to describe the what and how to embed.
        // This object is used when calling powerbi.embed.
        // This also includes settings and options such as filters.
        // You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
        var config = {
            type: 'report',
            // tokenType: models.TokenType.Embed,
            accessToken: accessToken,
            embedUrl: embedUrl,
            id: embedReportId,
            viewMode: models.ViewMode.View,
            // filters: filter,
            permissions: models.Permissions.All ,
            settings: {
                filterPaneEnabled: false,
                navContentPaneEnabled: false
            }
        };
        // Get a reference to the embedded report HTML element
        var tu11 = $('.tu11')[0];
        if ("" != "") {
            $("#RLS").prop('checked', true);
            $("#RLSdiv").show();
        }
        else
        {
            $("#RLS").prop('checked', false);
            $("#RLSdiv").hide();
        }
        if ("False" == "True") {
            $("#noRLSdiv").hide();
            $("#RLS").removeAttr("disabled");
            $("#RLS").change(function () {
                if ($(this).is(":checked")) {
                    $("#RLSdiv").show(300);
                } else {
                    $("#RLSdiv").hide(200);
                }
            });
        }
        else
        {
            $("#noRLSdiv").show();
        }
        var report = powerbi.embed(tu11, config);
    };

    // 确定
    var pingjieIndex1 = 0;
    $(".application").on("click",function () {
        var storeName = $(".details1").val();
        var commodity1Time1 = $(".details12").val();
        var commodity1Time2 = $("#usertype").val();
        if (storeName == 0 || commodity1Time2==''){
            alert("请选择完整选项");
            return false;
        };
        // 拼接图形盒子1
        pingjieIndex1++;
        var tu1Id = "reportContainer1";
        tu1Id = tu1Id + pingjieIndex1;
        console.log(tu1Id);
        var arrtx1 = [];
        arrtx1.push("<div class='tu11 no-border'" + "id=" +tu1Id +">");
        arrtx1.push("</div>");
        str0 = arrtx1.join('');
        $(".tu1").append(str0);
        // 删除其他元素
        $('.tu1'+' #'+tu1Id).siblings().remove();
        var arr = [];
        for (i=0;i<commodity1Time2.length ;i++ ){
            var text = "'"+commodity1Time2[i]+"'";
            console.log(text);
            arr.push(text);
        }
        var result = "("+arr+")";
        var result0 = arr;
        console.log(commodity1Time2);
        var myUrl = "https://app.powerbi.cn/reportEmbed?reportId=6f4afd96-4aee-4f73-aba3-75cf9f483614&groupId=ccc12464-fcfc-4fd0-ac4b-877eaad6b69b";
        if(commodity1Time2.length==1){
            var embedUrl = myUrl+"&filter=platform/platform eq"+" '"+storeName+"' "+"and season/code eq "+result0;
            $.ajax({
                url: pageUrl+'/api/common/getaccesstoken',
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    var msg = '';
                    if (data) {
                        var accessToken = data.data.accessToken.value;
                        tu1(accessToken,embedUrl);
                    }
                },
                error:  function (XMLHttpRequest, textStatus, errorThrown) {
                    // msg
                    var errorTips = XMLHttpRequest.responseJSON.msg;
                    if (errorTips=='Division by zero'){
                        $(".layer1 .content").html("数据错误");
                        $(".layer1").show();
                        console.log(errorTips);
                    } else if(errorTips=='Token has expired'){
                        $(".layer1 .content").html("令牌过期");
                        $(".layer1").show();
                        window.location.href="login.html";
                    }


                }

            });
        }else if(commodity1Time2.length>1){
            var embedUrl = myUrl+"&filter=platform/platform eq"+" '"+storeName+"' "+"and season/code in "+result;
             $.ajax({
                url: pageUrl+'/api/common/getaccesstoken',
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    var msg = '';
                    if (data) {
                        var accessToken = data.data.accessToken.value;
                        tu1(accessToken,embedUrl);
                    }
                },
                error:  function (XMLHttpRequest, textStatus, errorThrown) {
                    // msg
                    var errorTips = XMLHttpRequest.responseJSON.msg;
                    if (errorTips=='Division by zero'){
                        $(".layer1 .content").html("数据错误");
                        $(".layer1").show();
                        console.log(errorTips);
                    } else if(errorTips=='Token has expired'){
                        $(".layer1 .content").html("令牌过期");
                        $(".layer1").show();
                        window.location.href="login.html";
                    }


                }

            });
        };


    });



});